var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var async = require('async');
var DB_CONN_STR = 'mongodb://10.31.155.79:27017/happy';

router.get('/', function(req, res, next) {

   MongoClient.connect(DB_CONN_STR,function(err,db){
      if(err){
          console.log('数据库连接错误'+err);
          return ;
      }else{
        
        var conn = db.collection('book');


      
       conn.find({}).toArray(function(err,results){
          if(err){
            console.log('数据查询错误'+err);
            return ;
          }else{
            var info = results[0].books;
            console.log(info.length);
            res.render('book',{ title: '这是图书列表页',data:info});
            db.close();
          }
        })
      }
  })
});

router.get('/morebooks', function(req, res, next) {
    var pageNo = req.query.pageNo,
      pageNo = pageNo?pageNo:1,
      pageSize =8,
      count = 0,
      totalPage = 0;


      var findData = function(db,callback){
          var conn = db.collection('book');
          //此处还要2件事 查询列表数据  统计总记录
           async.parallel([
             function(callback){
               conn.find({}).toArray(function(err,results){
                 if(err){
                   return ;
                 }else{
                    totalPage = Math.ceil(results[0].books.length/pageSize);
                    count = results[0].books.length;

                    callback(null,'');
                 }
               })
             }
             ,
             function(callback){
               conn.find({}).toArray(function(err,results){
                  if(err){
                    return ;
                  }else{
                   
                    var arr = [];
                    var i = (pageNo-1)*pageSize;
                    var j = pageNo*pageSize;
                    if(j>results[0].books.length){
                        j=results[0].books.length;
                    }
                    for(i;i<j;i++ ){
                        arr.push(results[0].books[i]);                        
                    }
                    console.log(arr.length);
                    callback(null,arr);
                  }
               })
             }
           ],function(err,results){
            
              callback(results[1]);
              
           })

      }

      MongoClient.connect(DB_CONN_STR,function(err,db){
          if(err){
            return;
          }else{
            findData(db,function(results){
             
             res.render('morebooks',{
                pageNo:pageNo,
                totalPage:totalPage,
                count:count,
                list:results
              })
              db.close();
            })
          }
      })
});


router.post('/search', function(req, res, next) {
    var title = req.body.title;
    MongoClient.connect(DB_CONN_STR,function(err,db){
      if(err){
        console.log(err);
        return ;
      }else{
        var conn = db.collection('book');
         conn.find({}).toArray(function(err,results){
              if(err){
                console.log(err);
                return ;
              }else{
                var info = results[0].books;
                var reg= new RegExp(title);
                var target = [];
                for(var i = 0;i<info.length;i++){
                    if(reg.test(info[i].title)){
                        target.push(info[i]);
                    }
                }
                 res.render('search',{list:target});
                db.close();
              }
         })
      }
    })
   
});


router.get('/bookdetail', function(req, res, next) {
  var id = req.query.id;
  MongoClient.connect(DB_CONN_STR,function(err,db){
      if(err){
        console.log('数据库连接错误'+err);
        return ;
      }else{
        var conn = db.collection('book');
        var conn1 = db.collection('bookcomments');
        var target = null;
        var comments = [];
        
        async.parallel([
          conn.find({}).toArray(function(err,results){
            if(err){
              console.log('查询错误'+err);
              return ;
            }else{
                var info = results[0].books;
                
                for(var i = 0;i<info.length;i++){
                    if(info[i].id===id){
                        target = info[i];
                        break ;
                    }
                };               
            }
        }),
         conn1.find({}).toArray(function(err,results){
          if(err){
            console.log(err);
            retuen ;
          }else{
              var info = results;
              for(var i = 0;i<10;i++){
                comments.push(info[i]);
              }
              db.close();//关闭数据库;
          }
        })
        ],function(err,results){
          db.close();
        });
       
        res.render('bookdetail', { target:target,comments:comments});
      }
  });
  
});


router.post('/submit', function(req, res, next) {
    
   var email =  req.session.email;
    if(email){
        var content = req.body.content;
        var bookid = req.body.bookid;
        console.log(bookid);
        MongoClient.connect(DB_CONN_STR,function(err,db){
            if(err){
              console.log('数据库连接错误');
              return ;
            }else{
               function insertData(db,callback){
                  var conn = db.collection('bookcomments');
                  var data = {username:email,bookid:bookid,content:content};
                  conn.insert(data,function(err,results){
                      if(err) return ;
                      callback(results);
                  })
               };
              MongoClient.connect(DB_CONN_STR,function(err,db){
                if(err){
                  return;
                } else {
                    insertData(db,function(results){
                      res.redirect('/');
                      db.close();
                    })
                }
              });
            }
        })
    }else{
       res.send("<script>alert('登录信息过期，请重新登录');location.href='/login'</script>")
    }
})


module.exports = router;